/**
 * http://usejsdoc.org/
 * @Server dgram.createSocket 
 */
var dgram = require('dgram'),
	server = dgram.createSocket("udp4");

function resizeImage(url,width,height,newName,callback){
	/**获取imagemagick图片处理模块对象*/
	var im = require('imagemagick');
	
	/**调用resize 方法实现图片的压缩处理*/
	im.resize({
		srcPath:url,
		dstPath:newName,
		width:width,
		height:height
	},function(err,stdout,stderr){//压缩处理完成后，回调处理返回结果
		if(err){//异常时，返回-1表示执行出现错误
			callback(-1);
			console.log(err);
		}else{
			console.log(stdout);
			callback(stdout);
		}
	});
}

/** socket 监听 message 消息事件**/
server.on("message",function(msg,rinfo){
	var imageObject = JSON.parse(msg);
	/**调用resizeImage方法，实现图片压缩*/
	resizeImage(imageObject.url,imageObject.width,imageObject.height,imageObject.new_name,function(ret){
		var retJson;
		if(ret = -1){
			retJson = {'code':-1,'msg':'some error in resize image','data':{}};
		}else{
			retJson = {'code':0,'msg':'success','data':{'name':imageObject.new_name}};
		}
		
		/** 将json对象转化为json字符串，便于数据传输*/
		var retStr = JSON.stringify(retJson);
		var message = new Buffer(retStr);
		
		/** 回复字符数据到发送数据的客户端*/
		
		server.send(message,0,message.length,rinfo.port,rinfo.address);
	});
});

/** socket 监听 listening 事件**/
server.on("listening",function(){
	var address = server.address();
	console.log("server listening "+address.address + ":" + address.port);
});
/**绑定并开始监听端口，启动UDP SOCKET*/
server.bind(41234);